package com.windchime.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.windchime.blog.entity.Blog;
import com.windchime.blog.entity.Comment;
import com.windchime.blog.entity.User;
import com.windchime.blog.mapper.CommentMapper;
import com.windchime.blog.service.AdminService;
import com.windchime.blog.service.BlogService;
import com.windchime.blog.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.windchime.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 评论表 服务实现类
 * </p>
 *
 * @author WindChime
 * @since 2021-08-05
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private BlogService blogService;

    @Autowired
    private UserService userService;

    @Autowired
    private AdminService adminService;

    /**
     * 分页查询
     * @param page  当前页
     * @param limit 当前页条目数量
     * @return commentLists
     */
    @Override
    public PageInfo<Comment> selectCommentList(Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        List<Comment> comments = baseMapper.selectList(wrapper);

        for (Comment comment : comments) {
            comment.setBlogName(blogService.getById(comment.getBlogId()).getTitle());
            if (comment.getUserId() == 0) {
                comment.setCommentator("管理员");
            } else {
                comment.setCommentator(userService.getById(comment.getUserId()).getUsername());
            }
            if (comment.getParentId() == 0) {
                comment.setParentOff(false);
            } else {
                comment.setParentOff(true);
            }
            comment.setAdminOnOrOff(comment.getAdminId());
        }

        return new PageInfo<>(comments);
    }

    /**
     * 回复评论--后台
     * @param comment 评论
     * @return true
     */
    @Override
    public boolean replyComment(Comment comment) {
        Blog blog = blogService.getById(comment.getBlogId());
        blog.setCommentCount(blog.getCommentCount() + 1);
        blogService.updateById(blog);

        return baseMapper.insert(comment) > 0;
    }

    /**
     * 前台--保存评论
     * @param comment 评论对象
     */
    @Override
    public void saveComment(Comment comment) {
        //博客表评论数量加1
        Blog blog = blogService.getById(comment.getBlogId());
        blog.setCommentCount(blog.getCommentCount() + 1);
        blogService.updateById(blog);

        baseMapper.insert(comment);
    }

    //存放迭代找出的所有子代的集合
    private List<Comment> tempReplys = new ArrayList<>();

    /**
     * 根据博客ID获取该博客的评论
     * @param blogId 博客ID
     * @return comments
     */
    @Override
    public List<Comment> listCommentByBlogId(Long blogId) {
        // 查询出父节点
        List<Comment> comments = baseMapper.selectList(new QueryWrapper<Comment>().eq("blog_id", blogId).eq("parent_id", 0).orderByDesc("create_time"));
        for(Comment comment : comments){

            Integer userId = comment.getUserId();
            if (userId != 0) {
                comment.setUserName(userService.getById(comment.getUserId()).getUsername());
            } else {
                comment.setAdminName(adminService.getById(1).getUsername());
            }

            Integer parentUserId1 = comment.getUserId();
            List<Comment> childComments = baseMapper.selectList(new QueryWrapper<Comment>().eq("blog_id", blogId).eq("parent_id", comment.getId()));
            for (Comment childComment : childComments) {
                if (childComment.getUserId() != 0) {
                    childComment.setUserName(userService.getById(childComment.getUserId()).getUsername());
                } else {
                    comment.setAdminName(adminService.getById(1).getUsername());
                }
            }

            // 查询出子评论
            combineChildren(blogId, childComments, parentUserId1);
            comment.setReplyComments(tempReplys);
            tempReplys = new ArrayList<>();
        }
        return comments;
    }

    private void combineChildren(Long blogId, List<Comment> childComments, Integer parentUserId1) {
        // 判断是否有一级子评论
        if(childComments.size() > 0){
            // 循环找出子评论的id
            for(Comment childComment : childComments){
                childComment.setParentUserId(parentUserId1);

                if (childComment.getUserId() != 0) {
                    childComment.setUserName(userService.getById(childComment.getUserId()).getUsername());
                } else {
                    childComment.setAdminName(adminService.getById(1).getUsername());
                }

                //判断是否是管理员
                if (parentUserId1 == 0) {
                    childComment.setParentUserName(adminService.getById(1).getUsername());
                } else {
                    childComment.setParentUserName(userService.getById(parentUserId1).getUsername());
                }

                tempReplys.add(childComment);
                Integer childId = childComment.getId();
                // 查询出子二级评论
                recursively(blogId, childId, childComment.getUserId());
            }
        }
    }

    private void recursively(Long blogId, Integer childId, Integer parentUserId) {
        List<Comment> replayComments = baseMapper.selectList(new QueryWrapper<Comment>().eq("blog_id", blogId).eq("parent_id", childId));

        if(replayComments.size() > 0){
            for(Comment replayComment : replayComments){
                replayComment.setParentUserId(parentUserId);

                if (replayComment.getUserId() != 0) {
                    replayComment.setUserName(userService.getById(replayComment.getUserId()).getUsername());
                } else {
                    replayComment.setAdminName(adminService.getById(1).getUsername());
                }

                if (parentUserId == 0) {
                    replayComment.setParentUserName(adminService.getById(1).getUsername());
                } else {
                    replayComment.setParentUserName(userService.getById(parentUserId).getUsername());
                }

                Integer replayId = replayComment.getId();
                tempReplys.add(replayComment);
                recursively(blogId, replayId, replayComment.getUserId());
            }
        }
    }

}
